<?php
/**
 * A simple description for this script
 *
 * PHP Version 5.2.0 or Upper version
 *
 * @package    Paylog
 * @author     Hidehito NOZAWA aka Suin <http://suin.asia>
 * @copyright  2010 Hidehito NOZAWA
 * @license    http://www.gnu.org/licenses/gpl-2.0.html GNU GPL v2
 *
 */

class Paylog_Controller_Entry extends Paylog_Abstract_FormController
{
	protected $balanceHand = null;
	protected $groupHand   = null;
	protected $bookId = null;

	protected $groups = array();

	public function __construct()
	{
		parent::__construct();

		$this->balanceHand = new Paylog_Object_BalanceHandler;
		$this->groupHand   = new Paylog_Object_GroupHandler;
		$this->groupObjs   = $this->groupHand->loads();

		$this->bookId = Paylog::get('book_id');

		$this->_initItems();

		if ( !Paylog::$cms->isUser() )
		{
			Paylog::redirect("Please login");
		}

		$this->output['menu'] = $this->session['menu'];
		$this->output['book_id'] =& $this->bookId;
	}

	public function main()
	{
		$this->_validateAccess();
		parent::main();
	}

	protected function _initItems()
	{
		$today = date('Y-m-d');
		$tags  = array();

		foreach ( $this->groupObjs as $groupObj )
		{
			$groupId = $groupObj->getVar('id');
			$tags[$groupId] = '';
		}

		for ( $i = 0; $i < 10; $i ++ )
		{
			$this->input['items'][] = array(
				'date'  => $today,
				'name'  => '',
				'price' => '',
				'flow'  => Paylog_Object_Balance::FLOW_OUT,
				'tags'  => $tags,
			);
		}
	}

	protected function _validateAccess()
	{
		if ( !$this->bookId )
		{
			Paylog::redirect("Book is not selected.");
		}

		$bookHand = new Paylog_Object_BookHandler;

		if ( !$bookHand->isBookExists($this->bookId) )
		{
			Paylog::redirect("Book deos not exists.");
		}

		$relBookUserHand = new Paylog_Object_RelBookUserHandler;

		if ( !$relBookUserHand->isOwner(Paylog::$cms->userId) )
		{
			Paylog::redirect("Only owner can edit.");
		}
	}

	protected function _load(){}

	protected function _get()
	{
		$this->input['items'] = Paylog::post('items', $this->input['items']);
	}

	protected function _validate()
	{
		$token = Paylog::post('token');

		if ( !Paylog_Class_Ticket::check($token) )
		{
			$this->_addError("Ticket Error");
		}

		$items = $this->input['items'];
		$blanks = 0;

		foreach ( $items as $key => $item )
		{
			if ( !$item['name'] and !$item['price'] )
			{
				$blanks ++;
				continue;
			}

			if ( !$item['name'] )
			{
				$message = Paylog::msg("No.{1} item's name is blank.", $key);
				$this->_addError($message);
			}
			elseif ( !$item['price'] )
			{
				$message = Paylog::msg("No.{1} item's price is blank or zero.", $key);
				$this->_addError($message);
			}
			elseif ( preg_match('/([^0-9])/', $item['price']) )
			{
				$message = Paylog::msg("No.{1} item's price is not number.", $key);
				$this->_addError($message);
			}

			if ( !$item['date'] )
			{
				$message = Paylog::msg("No.{1} item's date is brank.", $key);
				$this->_addError($message);
			}
			elseif ( !preg_match('/^([0-9]{4})-([0-9]{2})-([0-9]{2})$/', $item['date'], $date) )
			{
				$message = Paylog::msg("No.{1} item's date format is invalid.", $key);
				$this->_addError($message);
			}
			elseif ( !checkdate($date[2], $date[3], $date[1]) )
			{
				$message = Paylog::msg("No.{1} item's date is invalid.", $key);
				$this->_addError($message);
			}
		}

		if ( count($items) == $blanks )
		{
			$message = Paylog::msg("No items was inputted.", $key);
			$this->_addError($message);
		}

		$this->_riseError();
	}

	protected function _preview(){}

	protected function _save()
	{
		$items = $this->input['items'];

		$relBalanceTagHand = new Paylog_Object_RelBalanceTagHandler;

		foreach ( $items as $item )
		{
			if ( !$item['name'] and !$item['price'] )
			{
				continue;
			}

			$balanceObj = $this->balanceHand->create();
			$balanceObj->setVar('date', $item['date']);
			$balanceObj->setVar('name', $item['name']);
			$balanceObj->setVar('flow', $item['flow']);
			$balanceObj->setVar('price', $item['price']);
			$balanceObj->setVar('uid', Paylog::$cms->userId);
			$balanceObj->setVar('book_id', $this->bookId);

			if ( !$this->balanceHand->save($balanceObj) )
			{
				$message = Paylog::msg("Could not insert item '{1}'", $item['name']);
				$this->_addError($message);
			}

			$balanceId = $balanceObj->getVar('id');

			foreach ( $item['tags'] as $tag )
			{
				$relBalanceTagObj = $relBalanceTagHand->create();
				$relBalanceTagObj->setVar('balance_id', $balanceId);
				$relBalanceTagObj->setVar('tag_id', $tag);

				if ( !$relBalanceTagHand->save($relBalanceTagObj) )
				{
					$message = Paylog::msg("Could not tag '{1}' to item '{2}'", $tag, $item['name']);
					$this->_addError($message);
				}
			}
		}

		$this->_riseError();

		$dates = array();

		foreach ( $items as $item )
		{
			if ( !$item['name'] and !$item['price'] )
			{
				continue;
			}

			$dates[] = $item['date'];
		}

		sort($dates, SORT_STRING);

		$firstDate = reset($dates);
		$lastDate  = end($dates);

		$extra = array(
			'book_id' => $this->bookId,
			'start'   => $firstDate,
			'end'     => $lastDate,
		);

		Paylog::redirect("Entry saved.", null, 'detail', null, $extra);
	}

	protected function _delete(){}

	protected function _form()
	{
		$this->_outputGroups();
		$this->output['token']  = Paylog_Class_Ticket::issue();
		$this->output['errors'] = $this->errors;
		$this->output['items']  = $this->input['items'];

		$this->_view();
	}

	protected function _outputGroups()
	{
		foreach ( $this->groupObjs as $groupObj )
		{
			$options = array();

			foreach ( $groupObj->tagObjs as $tagObj )
			{
				$options[] = array(
					'id'   => $tagObj->getVar('id'),
					'name' => $tagObj->getVar('name'),
				);
			}

			$this->output['groups'][] = array(
				'id'   => $groupObj->getVar('id'),
				'name' => $groupObj->getVar('name'),
				'options' => $options,
			);
		}
	}

	protected function _addError($msg)
	{
		$this->errors[] = Paylog::msg($msg);
	}

	protected function _riseError()
	{
		if ( count($this->errors) > 0 )
		{
			throw new Exception();
		}
	}
}

?>
